﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FERW.Models;
namespace FERW.Controllers
{
    public class TaskController : Controller
    {
        Model1 mo = new Model1();
        // GET: Task
        public ActionResult Index(int projectid = 0, string content = "",int taskstate=0)
        {
            var list = mo.Project.ToList();
            list.Insert(0, new Project() { ProjectName = "全部", ProjectID = 0 });
            ViewBag.ProjectID = new SelectList(list, "ProjectID", "ProjectName");
            var one = mo.Task.Where(p => p.Content.Contains(content) && (projectid == 0 || p.ProjectID == projectid)&&(taskstate==0||p.TaskState==taskstate)).ToList();
            return View(one);
        }
        public ActionResult Create()
        {
            ViewBag.ProjectID = new SelectList(mo.Project, "ProjectID", "ProjectName");
            return View();
        }
        [HttpPost]
        public ActionResult Create(Task task)
        {
            if (ModelState.IsValid)
            {
                task.AddTime = DateTime.Now;
                task.FinishedTime = null;
                task.TaskState = 1;
                mo.Task.Add(task);
                var res = mo.SaveChanges();
                if (res > 0)
                {
                    return RedirectToAction("Index");
                }
            }
            ViewBag.ProjectID = new SelectList(mo.Project, "ProjectID", "ProjectName");
            return View(task);
        }
        [HttpPost]
        public ActionResult Edit(int id)
        {
            if (ModelState.IsValid)
            {
                var list = mo.Task.FirstOrDefault(p => p.TaskID == id);
                if (list != null)
                {
                    list.FinishedTime = DateTime.Now;
                    var res = mo.SaveChanges() > 0;
                    return Json(res);

                }
            }
            return Json(false);
        }
        [HttpPost]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return Json("Index");
            }
            var task = mo.Task.Where(m => m.TaskID == id).FirstOrDefault();
            if (task == null)
            {
                return Json("Index");
            }
            mo.Task.Remove(task);
            var res = mo.SaveChanges();
            if (res > 0)
            {
                return Json(res);
            }
            return Json(false);
        }
    }
    }
